# server/src/search/ddg.py
import os
import requests
from .base import SearchProvider
from loguru import logger
import json

# DuckDuckGo搜索模块
class DuckDuckGoSearch(SearchProvider):
    def __init__(self):
        self.api_key = os.getenv("DDG_API_KEY")  # 从环境变量获取API密钥
        self.endpoint = "https://api.duckduckgo.com/"

        # 密钥缺失时警告
        if not self.api_key:
            logger.warning("DDG_API_KEY 未配置，搜索功能可能受限")

    def search(self, query: str, num_results: int = 3) -> str:
        try:
            if not self.api_key:
                raise ValueError("DuckDuckGo API 密钥未配置")
            
            params = {
                "q": query,
                "format": "json",
                "no_html": 1,
                "no_redirect": 1,
                "api_key": self.api_key  # 传递API密钥
            }

            response = requests.get(self.endpoint, params=params, timeout=10)
            response.raise_for_status()
            
            results = []
            for item in response.json().get("Results", [])[:num_results]:
                results.append({
                    "name": item.get("Text"),
                    "snippet": item.get("FirstURL"),
                    "url": item.get("FirstURL")
                })
            
            return json.dumps(results, ensure_ascii=False)[:1500]
        except Exception as e:
            logger.error(f"DuckDuckGo搜索失败：{str(e)}")
            return None